package uk.org.landeg.euler.problems;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

import uk.org.landeg.euler.problems.framework.AbstractProblem;
import uk.org.landeg.euler.problems.framework.ProblemLauncher;

public class Problem059 extends AbstractProblem {
	char[] cipher;

	public static void main(String[] args) {
		ProblemLauncher launcher = new ProblemLauncher(new Problem059());
		launcher.solve();
	}

	private char[] decode(char[] chars, char[] key) {
		char[] decoded = new char[chars.length];
		boolean space = false;
		for (int x = 0; x < chars.length; x++) {
			decoded[x] = (char) (chars[x] ^ key[x % key.length]);
			if (decoded[x] < ' ' || decoded[x] > '~') {
				return null;
			}
			if (decoded[x] == ' ') {
				space= true;
			}
		}
		if (!space) {
			return null;
		}
		return decoded;
	}

	@Override
	public String getDescription() {
		return "Decode the cipher";
	}

	@Override
	public Integer getProblemNumber() {
		return 59;
	}

	public void loadCipher() {
		BufferedReader reader;
		try {
			reader = new BufferedReader(new FileReader("data/cipher1.txt"));
			String[] elmts = reader.readLine().split(",");
			cipher = new char[elmts.length];
			int idx = 0;
			for (String s : elmts) {
				cipher[idx++] = (char) (Integer.parseInt(s));
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public Object solve() {
		loadCipher();
		char[] decoded, key;
		String theString;
		int sum = 0;
//		System.out.println(new String (cipher));
		for (char a = 'a'; a <= 'z'; a++) {
			for (char b = 'a'; b <= 'z'; b++) {
				for (char c = 'a'; c <= 'z'; c++) {
					key = new char[] {a,b,c};
					decoded = decode(cipher, key);
					if (decoded != null) {
//						System.out.println(decoded);
						theString = new String (decoded);
						if (theString.contains(" and ") && theString.contains(" the ")) {
							System.out.println(Arrays.toString(key) + "\t" + theString);
							for (char dc : decoded) {
								sum += (int)dc;
							}
						}
					}
				}
			}
		}
		return sum;
	}
}
